package com.nekonomics
package api.route

import api.dto.request.ShipOrderReq
import api.dto.response.OrderDetailDto
import api.dto.response.RspEncoder.*
import domain.service.MerchantService
import domain.service.util.TokenService

import zio.*
import zio.http.*
import zio.http.Method.*
import zio.json.*


object MerchantRoute {

  val routes = baseApiPath / "merchant" / Routes(

    GET /"ads" / "order-weekly-summary" -> handler { (req: Request) =>
      for {
        jwt <- extractJwt(req)
        userId <- ZIO.serviceWithZIO[TokenService](_.verifyToken(jwt))
        merchant <- ZIO.serviceWithZIO[MerchantService](_.findByUserId(userId))
        data <- ZIO.serviceWithZIO[MerchantService](_.weeklyOrderSummary(merchant.id))
        rsp = data.toRsp.toJson
      } yield Response.json(rsp)
    },

    GET / "ads" /"top10-daily" -> handler { (req: Request) =>
      for {
        jwt <- extractJwt(req)
        userId <- ZIO.serviceWithZIO[TokenService](_.verifyToken(jwt))
        merchant <- ZIO.serviceWithZIO[MerchantService](_.findByUserId(userId))
        data <- ZIO.serviceWithZIO[MerchantService](_.top10Products(merchant.id))
        rsp = data.toRsp.toJson
      } yield Response.json(rsp)

    },

    GET / "orders" -> handler { (req: Request) =>
      for {
        jwt <- extractJwt(req)
        userId <- ZIO.serviceWithZIO[TokenService](_.verifyToken(jwt))
        merchant <- ZIO.serviceWithZIO[MerchantService](_.findByUserId(userId))
        orders <- ZIO.serviceWithZIO[MerchantService](_.listOrders(merchant.id))
        rsp = orders.toRsp.toJson
      } yield Response.json(rsp)
    },

    GET / "products" -> handler { (req: Request) =>
      for {
        jwt <- extractJwt(req)
        userId <- ZIO.serviceWithZIO[TokenService](_.verifyToken(jwt))
        merchant <- ZIO.serviceWithZIO[MerchantService](_.findByUserId(userId))
        products <- ZIO.serviceWithZIO[MerchantService](_.listProducts(merchant.id))
        rsp = products.toRsp.toJson
      } yield Response.json(rsp)
    },

    POST / "orders" / "ship" -> handler { (req: Request) =>
      for {
        jwt <- extractJwt(req)
        shipReq <- extractJsonBody[ShipOrderReq](req)
        userId <- ZIO.serviceWithZIO[TokenService](_.verifyToken(jwt))
        _ <- ZIO.serviceWithZIO[MerchantService](_.findByUserId(userId))
        orderId = shipReq.orderId
        _ <- ZIO.serviceWithZIO[MerchantService](_.shipOrder(orderId))
        rsp = "success".toRsp.toJson
      } yield Response.json(rsp)
    }

  )
}
